package com.rockcent.common;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by HK on 16/8/16.
 * 路由文件
 * 1.规范ID 表明是路径的变量参数: 例如
 * PRODUCT_$ID = "/product/{id}";
 * $ID = {id}
 */

public class BaseRoutes {
    private Map<String, String> paths = new HashMap<>();

    // 用于页面路由 start
    public BaseRoutes() throws IllegalAccessException {
        Field[] fields = this.getClass().getFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            paths.put(field.getName(), (String) field.get(this));
        }
    }

    // 路由的参数匹配规则
    private Pattern pattern = Pattern.compile("\\{(.*?)\\}");

    /**
     * 在开发环境的时候,没有nginx做转发,所以要加上 /main 做为前缀 http://localhost:8831/main 才可以访问首页
     * uat 环境 http://uat.www.rockcent.com
     * production 环境 http://www.rockcent.com
     * <p>
     * 有参数的例子:
     * http://localhost:8831/main/product/{id} 生成链接为 http://localhost:8831/main/product/1
     *
     * @param key
     * @param params {id} 替换为一个参数
     * @return
     */
    public String path(String key, String... params) {
        String path = paths.get(key);
        if (params != null) {
            Matcher matcher = pattern.matcher(path);
            for (int i = 0; i < params.length; i++) {
                if (matcher.find()) {
                    path.replace(matcher.group(), params[0]);
                }
            }

        }
        return path;
    }

    public String path(String key) {
        return paths.get(key);
    }

    // 用于页面路由 end
}
